package com.nitty.cash.loop.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.fragment.app.FragmentActivity
import com.lib.common.shapeview.builder.ShapeDrawableBuilder
import com.lib.common.shapeview.drawable.ShapeGradientOrientation
import com.lib.common.shapeview.drawable.ShapeGradientType
import com.nitty.cash.loop.R
import com.nitty.cash.loop.base.app.NittyStackManager
import com.nitty.cash.loop.databinding.UiRootviewBinding
import com.nitty.cash.loop.ui.activity.LaunchAct
import com.nitty.cash.loop.ui.dialog.NittyLoading
import com.nitty.cash.loop.utils.NittyTitleBarUtil
import com.nitty.cash.loop.utils.NittyToastManager

/**
 * BaseActivity
 * @Author wwdeng
 * @CreateTime: 2024/11/22 10:32
 * @Annotation：基类 Activity
 */
abstract class BaseActivity : FragmentActivity(), IBaseView {

    lateinit var rootViewBinding: UiRootviewBinding

    /* 是否拦截返回按钮，默认不拦截直接返回 */
    private var isInterceptBack = false
    /* 点击外部是否需要隐藏软键盘 */
    private var isHideSoftInput = true

    /* 退出程序提示 */
    private var mExitTips = "Press again to exit the app"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (savedInstanceState != null && this::class.java.simpleName != LaunchAct::class.java.simpleName){
            onIntent(LaunchAct::class.java)
            return
        }
        NittyTitleBarUtil.transparentStatusBar(this)
        NittyTitleBarUtil.setStatusBarLightMode(this, true)
        setContentView(getNittyRootView())
        initNittyView()
        initNittyListener()
    }

    private var hasLoadedData = false
    override fun onResume() {
        super.onResume()
        if (!hasLoadedData) {
            loadNittyData()
            hasLoadedData = true
        }
    }

    protected abstract fun getNittyRootView(): View?

    protected abstract fun initNittyView()

    protected abstract fun initNittyListener()

    protected abstract fun loadNittyData()

    /**
     * 重试
     */
    protected abstract fun requestTryAgain()

    override fun setContentView(rootView: View?) {
        rootViewBinding = UiRootviewBinding.inflate(layoutInflater)
        rootViewBinding.rootTitleBar.setPadding(0, NittyTitleBarUtil.getStatusBarHeight(),0,0)
        rootViewBinding.rootBackgroundLable.visibility = View.GONE
        if (rootView != null){
            rootViewBinding.rootContainer.addView(rootView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        }
        setNittyTitleBarVisibility(View.GONE)
        //返回
        rootViewBinding.rootBack.setOnClickListener {
            onBackAction()
        }
        super.setContentView(rootViewBinding.root)
    }

    /**
     * 设置背景透明
     */
    fun setNittyRootParentTransparent(){
        setNittyRootParentBackgroundColor(getColor(R.color.transparent))
    }

    /**
     * 设置背景颜色
     */
    fun setNittyRootParentBackgroundColor(color: Int){
        rootViewBinding.rootLayout.shapeDrawableBuilder.setSolidColor(color).intoBackground()
//        rootViewBinding.rootLayout.setBackgroundColor(color)
    }

    /**
     * 设置背景颜色
     */
    fun setNittyRootParentBackgroundColors(startColor: Int,endColor: Int){
        rootViewBinding.rootLayout.shapeDrawableBuilder
            .setSolidGradientType(ShapeGradientType.LINEAR_GRADIENT)
            .setSolidGradientOrientation(ShapeGradientOrientation.START_TO_END)
            .setSolidGradientColors(startColor,endColor)
            .intoBackground()
//        rootViewBinding.rootLayout.setBackgroundColor(color)
    }

    /**
     * 设置顶部背景图片是否显示
     */
    fun setNittyRootBackgroundLableVisibility(visibility: Int) {
        rootViewBinding.rootBackgroundLable.visibility = visibility
    }

    /**
     * 设置顶部背景图片
     */
    fun setNittyRootBackgroundLableRes(resId: Int) {
        setNittyRootBackgroundLableVisibility(View.VISIBLE)
        rootViewBinding.rootBackgroundLable.setImageResource(resId)
    }

    /**
     * @功能描述：是否显示Toolbar
     */
    fun setNittyTitleBarVisibility(visibility: Int) {
        rootViewBinding.rootTitleBar.visibility = visibility
    }

    /**
     * 设置toolBar背景颜色
     */
    fun setNittyTitleBarColor(color: Int) {
        setNittyTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootTitleBar.setBackgroundColor(color)
    }

    /**
     * 设置toolBar背景图片
     */
    fun setNittyTitleBarRes(res: Int) {
        setNittyTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootTitleBar.setBackgroundResource(res)
        rootViewBinding.rootTitleBar.setPadding(0, 0, 0, 0)
    }

    /**
     * 设置是否显示返回
     */
    fun setNittyBackBtnVisibility(visibility: Int) {
        rootViewBinding.rootBack.visibility = visibility
    }

    /**
     * 设置返回按钮图标
     */
    fun setNittyBackBtnRes(res: Int){
        setNittyBackBtnVisibility(View.VISIBLE)
        rootViewBinding.rootBack.setImageResource(res)
    }

    /**
     * 是否显示Title
     */
    fun setNittyTextTitleVisibility(visibility: Int){
        rootViewBinding.rootTitle.visibility = visibility
    }

    /**
     * 设置Title颜色
     */
    fun setNittyTextTitleColor(color: Int) {
        setNittyTextTitleVisibility(View.VISIBLE)
        rootViewBinding.rootTitle.setTextColor(color)
    }

    /**
     * 设置Title
     */
    fun setNittyTextTitle(text: String) {
        setNittyTextTitleVisibility(View.VISIBLE)
        rootViewBinding.rootTitle.text = text
    }

    /**
     * 设置Title对齐方式
     * 默认：Gravity.LEFT
     */
    fun setNittyTextTitleGravity(gravity: Int){
        setNittyTextTitleVisibility(View.VISIBLE)
        rootViewBinding.rootTitle.gravity = gravity
    }

    /**
     * 设置是否显示右侧图标
     */
    fun setNittyRightBtnVisibility(visibility: Int){
        rootViewBinding.rootCustomer.visibility = visibility
    }

    /**
     * 设置右侧按钮图标
     */
    fun setNittyRightBtnRes(res: Int){
        setNittyRightBtnVisibility(View.VISIBLE)
        rootViewBinding.rootCustomer.setImageResource(res)
    }

    override fun getContext(): Context {
        return this
    }

    override fun showNittyLoading() {
        showNittyLoading(isTOuchOut = false, isCancel = true)
    }

    fun showNittyLoading(msg: String="") {
        showNittyLoading(isTOuchOut = false, isCancel = true,msg)
    }

    fun showNittyLoading(isTOuchOut: Boolean, isCancel: Boolean, msg: String="") {
        NittyLoading.show(this, isTOuchOut, isCancel,msg)
    }

    override fun hiddenNittyLoading() {
        NittyLoading.dismiss(this)
    }

    /**
     * toast
     * @param msg
     */
    override fun showNittyToast(msg: String?) {
        NittyToastManager.showShortText(this, msg)
    }

    /**
     * toast
     * @param msg
     */
    fun showNittyToastDuration(msg: String?, duration: Int) {
        NittyToastManager.showTextDuration(this, msg, duration)
    }

    /**
     * 设置退出程序提示语
     */
    fun setExitTips(tips: String){
        this.mExitTips = tips
    }

    /**
     * 页面跳转（不带参数）
     *
     * @param T
     */
    open fun onIntent(T: Class<*>?) {
        startActivity(Intent(this, T))
    }

    /**
     * 页面跳转（带参数）
     *
     * @param T
     * @param bundle
     */
    open fun onIntent(T: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, T)
        if (bundle != null) intent.putExtras(bundle)
        startActivity(intent)
    }

    /* 隐藏键盘 */
    fun onHideSoftInput(v: View) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(v.windowToken, 0)
    }

    /**
     * 隐藏软键盘
     */
    fun onHideSoftInput() {
        val window = this.window
        var view = window.currentFocus
        if (view == null){
            view = window.decorView
        }
        onHideSoftInput(view)
    }

    /* 显示键盘 */
    fun onShowSoftInput(v: View) {
        val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
        v.requestFocus()
    }

    /**
     * 点击外部隐藏键盘
     * 滑动不隐藏
     */
    private var downY = 0.0f
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when(ev.action){
            MotionEvent.ACTION_DOWN -> {
                downY = ev.y
            }
            MotionEvent.ACTION_UP -> {
                // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
                val v = currentFocus
                if (isShouldHideInput(v, ev) && isHideSoftInput && downY == ev.y) {
                    hideSoftInput(v!!.windowToken)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = (left + v.getWidth())
            return if (event.x > left && event.x < right && event.y > top && event.y < bottom) {
                // 点击EditText的事件，忽略它。
                false
            } else {
                true
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /* 返回 */
    fun onBackAction() {
        if (!isInterceptBack) { //不拦截，直接返回
            finish()
        }
    }

    /* 是否拦截返回按钮 */
    fun isInterceptBack(isBackExit: Boolean) {
        isInterceptBack = isBackExit
    }

    /* 点击外部是否需要隐藏软键盘 */
    fun isHideSoftInputClickTouchOut(isTouchOut: Boolean){
        isHideSoftInput = isTouchOut
    }

    /* 向Activity中添加fragment */
    fun addContainerFragement(layout: Int, fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .add(layout, fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /* 替换Activity中的fragment */
    fun replaceContainerFragement(layout: Int, fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .replace(layout, fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /* 显示Activity中的fragment */
    fun showContainerFragement(fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .show(fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /* 隐藏Activity中的fragment */
    fun hideContainerFragement(fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .hide(fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /* 移除Activity中的fragment */
    fun removeContainerFragement(fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .remove(fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * @功能描述：是否连续两次返回退出
     */
    private var isBackExit = false
    fun setBackExit(isBackExit: Boolean) {
        this.isBackExit = isBackExit
    }

    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (isBackExit) {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    showNittyToast(mExitTips)
                    exitTime = System.currentTimeMillis()
                } else {
//                    System.exit(0);
                    NittyStackManager.finishAllActivity()
                }
            } else {
                onBackAction()
            }
            return true
        }
        //        if (keyCode == KeyEvent.KEYCODE_BACK && mActivitys.size() == 1) {
//            startActivity(new Intent("icloudwave.hhour.home"));
//        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
//        NetworkUtils.onCancelRequest()
    }
}